from flask import Flask, jsonify
import os
import pymysql
from pymysql.cursors import DictCursor
import logging
from logging.handlers import RotatingFileHandler

app = Flask(__name__)

# 配置日志
log_path = '/app/logs/flask/app.log'
os.makedirs(os.path.dirname(log_path), exist_ok=True)
handler = RotatingFileHandler(log_path, maxBytes=10000000, backupCount=5)
handler.setFormatter(logging.Formatter(
    '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
))
app.logger.addHandler(handler)
app.logger.setLevel(logging.INFO)

def get_db_connection():
    try:
        connection = pymysql.connect(
            host=os.getenv('MYSQL_HOST', 'mysql'),
            database=os.getenv('MYSQL_DATABASE', 'testdb'),
            user=os.getenv('MYSQL_USER', 'user'),
            password=os.getenv('MYSQL_PASSWORD', 'password'),
            cursorclass=DictCursor,
            ssl=None,
        )
        app.logger.info('Database connection successful')
        return connection
    except pymysql.Error as e:
        app.logger.error(f"Error connecting to MySQL: {e}")
        return None

@app.route('/')
def index():
    app.logger.info('Index page accessed')
    return jsonify({"message": "Welcome to Flask-MySQL-K3s Application!"})

@app.route('/items')
def get_items():
    app.logger.info('Attempting to fetch items from database')
    connection = get_db_connection()
    if connection:
        try:
            with connection.cursor() as cursor:
                cursor.execute("SELECT * FROM items")
                items = cursor.fetchall()
            connection.close()
            app.logger.info(f'Successfully retrieved {len(items)} items')
            return jsonify(items)
        except pymysql.Error as e:
            app.logger.error(f'Database error: {e}')
            return jsonify({"error": str(e)}), 500
    app.logger.error('Database connection failed')
    return jsonify({"error": "Database connection failed"}), 500

if __name__ == '__main__':
    app.logger.info('Flask application starting')
    app.run(host='0.0.0.0', port=5000) 